package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @Autowired
    private RedisTemplate redisTemplate;


    //添加菜品（非常复杂）
    @PostMapping
/*//    将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "dishCache",allEntries = true)*/
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.save(dishDto);
        //需要删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("新增菜品保存成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<IPage<Dish>> pageQuery(Integer page, Integer pageSize, String name) {
        Page<Dish> objectPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //开始查询
        dishService.page(objectPage, wrapper);

        //list(Dish) 转换为 list<Dto>
        ArrayList<DishDto> objects = new ArrayList<>();

        long total = objectPage.getTotal();
        objectPage.getTotal();
        //方法一
        List<Dish> list = objectPage.getRecords();
        HashMap map = new HashMap();
        map.put("total", total);
        for (Dish dish : list) {
            //获取分类菜品id
            Long id = dish.getCategoryId();
            //分类数据
            Category byId = categoryService.getById(id);
            //获取当前分类名称
            String byIdName = byId.getName();
            //创建一个对象
            DishDto dishDto = new DishDto();
            //list(Dish) 转换为 list<Dto>
            dishDto.setCategoryName(byIdName);

            BeanUtils.copyProperties(dish, dishDto);
            objects.add(dishDto);
        }
        //            ===================================
        //方法二
//            objects.stream().map((dish) -> {
//                //获取分类菜品id
//                Long id = dish.getCategoryId();
//                //分类数据
//                Category byId = categoryService.getById(id);
//                //获取当前分类名称
//                String byIdName = byId.getName();
//                //创建一个对象
//                DishDto dishDto = new DishDto();
//                //list(Dish) 转换为 list<Dto>
//                BeanUtils.copyProperties(dish, dishDto);
//                dishDto.setCategoryName(byIdName);
//                return dishDto;
//            }).collect(Collectors.toList());
//            =========================================
        //将dish数据翻到dishDto里面
        // 方法一
//            dishDto.setCreateTime(dish.getCreateTime()); ... ...
        //方法二

        map.put("dish", objectPage);
        return R.success(objectPage);
    }

    //根据id查询菜品的信息和对应的口味信息
    @GetMapping("/{id}")
    public R queryById(@PathVariable Long id) {
        DishDto dishDtoById = dishFlavorService.getDishDtoById(id);
        return R.success(dishDtoById);
//
    }

    //修改菜品
    @PutMapping
/*    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "dishCache",allEntries = true)*/
    public R<String> Update(@RequestBody DishDto dishDto) {
        dishFlavorService.updateDish(dishDto);
        //需要删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功!");
    }


//   =====================以下需要自己写================================

    //删除 1 \ 不删除 0
    @DeleteMapping
/*    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "dishCache",allEntries = true)*/
    public R<String> deleteDishs(@RequestParam List<Long> ids) {

        dishService.delectByIdDish(ids);
        //需要删除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }


    //  起售 1  \    停售  0
    @PostMapping("/status/{status}")
/*    //将数据从缓存中清除(清除所有的缓存数据)
    @CacheEvict(value = "dishCache",allEntries = true)*/
    public R<String> updateStatus(@PathVariable Integer status,
                                  @RequestParam List<Long> ids) {
        dishService.updateDish(status, ids);
        //需要删除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("操作成功");
    }

    /**
     * 套餐添加数据
     *
     * @return
     */
    @GetMapping("/list")
 /*   //查看缓存是否有数据，有则直接返回缓存数据，没有，则调用方法返回值把数据添加进去
    @Cacheable(value = "dishCache",key = "#categoryId + '_' + #status")*/
    public R<List<DishDto>> addishes(Dish dish) {
        //缓存
        List<DishDto> arrayList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //从redis中取出缓存数据
        arrayList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (arrayList != null) {
            //存在
            return R.success(arrayList);
        }


        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(wrapper);
        //把dish 转换为 dishdto，并返回
        arrayList = new ArrayList<>();
        for (Dish dish1 : list) {
            //把 dish的每一个值，转换为dishdto中
            DishDto dto = new DishDto();
            //把值(属性)复制到dto
            BeanUtils.copyProperties(dish1, dto);
            //把值(口味)数据，复制到dto
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dish.getId());
            //拿到值
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            dto.setFlavors(flavors);
            //把值添加进去
            arrayList.add(dto);
        }
        //不存在则存入(缓存)
        redisTemplate.opsForValue().set(key, arrayList);

        return R.success(arrayList);
    }





}
